from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy.orm.session import Session

from airflow.models.base import Base
from airflow.utils import dates
from airflow.utils.session import provide_session


class AuthRoleResource(Base):
    """the class to get user info."""

    __tablename__ = "idata_auth_role_resource"
    __table_args__ = {"useexisting": True}

    id = Column(Integer, primary_key=True, autoincrement=True)
    resource_id = Column(Integer)
    role_id = Column(Integer)
    create_time = Column(DateTime)

    def __init__(self,resource_id,role_id,create_time):
        self.resource_id = resource_id
        self.role_id = role_id
        self.create_time = create_time

    @staticmethod
    @provide_session
    def get_role_resource(id, session: Session = None):
        return session.query(AuthRoleResource).filter(AuthRoleResource.id == id).first()

    @staticmethod
    @provide_session
    def get_roles_resources(session: Session = None):
        return session.query(AuthRoleResource).all()

    @staticmethod
    @provide_session
    def get_roles_resources_page(page, session: Session = None):
        return session.query(AuthRoleResource).order_by(AuthRoleResource.create_time).paginate(page, 10, error_out=False)

    @staticmethod
    @provide_session
    def add_roles_resources(role_resource, session: Session = None):
        return session.add(role_resource)

    @staticmethod
    @provide_session
    def delete_role_resource(id, session: Session = None):
        session.query(AuthRoleResource).filter(AuthRoleResource.id == id).delete()

    @staticmethod
    @provide_session
    def delete_role_resource_by_roleid(role_id, session: Session = None):
        session.query(AuthRoleResource).filter(AuthRoleResource.role_id == role_id).delete()

    @staticmethod
    @provide_session
    def delete_role_resource_by_resourceid(resource_id, session: Session = None):
        session.query(AuthRoleResource).filter(AuthRoleResource.resource_id == resource_id).delete()

    @staticmethod
    @provide_session
    def update_role_resource(role_resource, session: Session = None):
        result = session.query(AuthRoleResource).filter(AuthRoleResource.id == role_resource.id).first()
        if result is None:
            return
        else:
            return session.merge(role_resource)

    def to_json(self):
        if self is None:
            return None
        data = {
            'id': self.id,
            'resource_id': self.resource_id,
            'role_id': self.role_id,
            'create_time': dates.to_milliseconds(self.create_time),
            'enable': self.enable
        }
        return data






